import { message, Upload, Typography } from "antd";
import { InboxOutlined } from "@ant-design/icons";
import React from "react";

const { Dragger } = Upload;
const { Title } = Typography;

interface FileUploaderProps {
  onUpload: (
    file: File,
    uploadParam?: Record<string, any>
  ) => Promise<any> | void;
  uploadParam?: Record<string, any>;
  title?: string;
  onUploading?: (isUploading: boolean) => void;
  multiple?: boolean;
  accept?: string;
}

const FileUploader: React.FC<FileUploaderProps> = ({
  onUpload,
  uploadParam = {},
  title = "投标文件上传",
  onUploading,
  multiple = true,
  accept = ".xlsx,.xls",
}) => {
  const handleCustomRequest = async (options: any) => {
    const { file } = options; // 注意：这里 file 可能是 string | File | Blob

    if (!(file instanceof File)) {
      message.error("上传失败：文件格式不正确");
      return;
    }

    if (onUploading) {
      onUploading(true);
    }

    try {
      await onUpload(file, uploadParam);
      message.success(`${file.name} 上传成功`);
      if (options.onSuccess) {
        options.onSuccess(null, file);
      }
    } catch (error: any) {
      message.error(`${file.name} 上传失败：${error.message || "未知错误"}`);
      if (options.onError) {
        options.onError(error);
      }
    } finally {
      if (onUploading) {
        onUploading(false);
      }
    }
  };

  return (
    <>
      <Title level={4} style={{ marginBottom: 16 }}>{title}</Title>
      <Dragger
        customRequest={handleCustomRequest}
        multiple={multiple}
        accept={accept}
        showUploadList={false}
      style={{ padding: "20px" }}
    >
      <p className="ant-upload-drag-icon">
        <InboxOutlined />
      </p>
      <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
      <p className="ant-upload-hint">可以上传单个或多个文件，支持的格式包括：{accept}</p>
    </Dragger>
    </>
  );
};

export default FileUploader;
